package cn.ffcs.share.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;

import cn.ffcs.base.web.BaseAction;
import cn.ffcs.base.web.PageControl;
import cn.ffcs.common.model.Attach;
import cn.ffcs.common.service.AttachService;
import cn.ffcs.share.model.ShareReference;
import cn.ffcs.share.service.ShareReferenceService;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.system.dict.model.DictType;
import cn.ffcs.system.dict.service.DictService;
import cn.ffcs.system.dict.service.DictTypeService;
import cn.ffcs.util.context.ApplicationContextUtil;
import cn.ffcs.util.properties.PropertiesUtil;

/**
 * 
 * 共享资料action层，实现页面业务逻辑<br/> <table>
 * <tr>
 * <td>负责人/principal: </td>
 * <td colspan="2">pany</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author pany
 * @version $Id$
 */
public class ShareReferenceAction<P extends ShareReference> extends
        BaseAction<P>
{
    private static final int BUFFER_SIZE = 512 * 1024;
    /** 业务POJO **/
    private P shareReference;
    /** 资料类型数据 **/
    private List<Dict> lRefType;
    /** 密級类型数据 **/
    private List<Dict> lSecretType;
    /** 共享资料类型数据 **/
    private List<P> shareRefList;
    /** 数据字典服务 **/
    private DictService dictService;
    /** 数据字典类型服务 **/
    private DictTypeService dictTypeService;
    /** 共享资料服务 **/
    private ShareReferenceService shareReferenceService;
    /** 附件列表数据 **/
    private List<Attach> attachs;
    /** 附件服务 **/
    private AttachService attachService;
    /** 附件上传 **/
    private List<File> uploads;
    /** 上传附件名称 **/
    private List<String> fileNames;
    /** 上传附件名称 **/
    private List<String> uploadContentTypes;
    /** ftp文件 **/
    private List<String> ftpFile;
    /** properties配置ftp路径 **/
    private String ftpUrl;
    /** 上传附件最大 **/
    private String ftpMaxSize;
    
    /** 当前资料细类类型 **/
    private String refType;
    /** 当前资料细类类型名称 **/
    private String refTypeName;
    /** 当前资料大类类型 **/
    private String dictType;
    /** 当前资料大类类型 **/
    private DictType currDictType;
    /** 当前资料大类类型 **/
    private Dict currDict;
    
    /** 首页显示信息数据 **/
    private List itvList;
    private List shopList;
    private List markList;
    private List comList;
    private List mdocList;
    private List notRefList;
    private List bizProcList;
    private List weakReportList;
    /**
     * 
     * 初始化业务数据
     * @return
     */
    @SuppressWarnings("unchecked")
    public String init(){
        this.initDict("SECRET");
        if(refType==null||"".equals(refType))
            refType="_SHARE";
        this.initDict(refType);

        if (shareReference!=null && shareReference.getId()!=null){
            Criterion cond1 = Restrictions.eq("refEntity", shareReference.getClass().getName());
            Criterion cond2 = Restrictions.eq("refEntityID", shareReference.getId().toString());
            Criterion condAttach = Restrictions.and(cond1, cond2);
            attachs=attachService.findBy(condAttach);
        }
        
        this.setFtpUrl(PropertiesUtil.readValue(
                "/poc-ftp.properties", "ftp.url"));
        this.setFtpMaxSize(PropertiesUtil.readValue("/poc-ftp.properties","ftp.maxSize"));
        return SUCCESS;
    }
    
    /**
     * 
     * 初始化字典数据
     * @return
     */
    @SuppressWarnings("unchecked")
    public void initDict(String sDictType){
        if(sDictType==null||sDictType.equals("")){
            return;
        }
        Criterion cond = Restrictions.like("keyValue", "%" + sDictType + "%");
        List dictType = dictTypeService.findBy(cond);
        if (dictType != null && dictType.size() > 0)
        {
            for (int i = 0; i < dictType.size(); i++)
            {
                Criterion dtcond = Restrictions.eq("dictType.id",
                        ((DictType) dictType.get(i)).getId());
                if (sDictType.equals("SECRET"))
                {
                    lSecretType = dictService.findBy(dtcond);
                    break;
                }
                else
                {
                    if(lRefType==null){
                        lRefType=dictService.findBy(dtcond);
                    }
                    else{
                        lRefType.addAll(dictService.findBy(dtcond));
                    }
                }
            }
        }
        else
        {
            if (sDictType.equals("SECRET"))
            {
                lSecretType = new ArrayList();
            }
            else if (sDictType.equals("SHARE_TYPE"))
                lRefType = new ArrayList();
        }
        return;
    }
    /**
     * 
     * 保存操作
     * @return
     */
    public String saveOrUpdate()
    {
        //初始化数据
        init();        

        //保存产品资料数据
        baseService.saveOrUpdate(shareReference);
        
        // 新增附件是否发布
        List<String> isPublishs = null;
        /** 是否有ftp上传 **/
        boolean isFtp = false;
        List<String> isFtps = null;
        /** ftpFile 
        List<String> ftpFile = null;**/
        if (uploads != null && uploads.size() > 0)
        {
            String[] cbPublishs = getContextObjects("isPublishs");
            String[] cbFtps = getContextObjects("isFtp");
            isPublishs = new ArrayList<String>();
            isFtps = new ArrayList<String>();
            for (String cbPublish : cbPublishs)
            {
                if (cbPublish.equalsIgnoreCase("1")
                        || cbPublish.equalsIgnoreCase("2"))
                {
                    if (cbPublish.equalsIgnoreCase("2"))
                    {
                        cbPublish = "0";
                    }
                    isPublishs.add(cbPublish);
                }
            }
            int i=0;
            for (i=0;i<uploads.size();i++)
            {
                String cbFtp = cbFtps[i];
                if (!cbFtp.equalsIgnoreCase("2") && uploads.get(i).length() > Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("1");
                }
                if (!cbFtp.equalsIgnoreCase("2") && uploads.get(i).length() <= Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("0");
                }
                if (cbFtp.equalsIgnoreCase("2") && uploads.get(i).length() > Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("1");
                }
                if (cbFtp.equalsIgnoreCase("2") && uploads.get(i).length() <= Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("0");
                }
                if (cbFtp.equalsIgnoreCase("1"))
                {
                    isFtp = true;
                }
            }
        }

        
        //保存附件
        if(uploads!=null)
        {
            int i=0;
            for (i=0;i<uploads.size();i++){
                try{
                    File file=uploads.get(i);
                    if(isFtps.get(i).equals("0")){
                        byte[] result=new byte[BUFFER_SIZE]; 
                        result=FileUtils.readFileToByteArray(file);
                        FileUtils.forceDelete(file);
                        
                        String fileName=this.fileNames.get(i);
                        String fullName=fileName;
                        String name=fullName.substring(0,fullName.lastIndexOf("."));
                        String prefix=fullName.substring(fullName.lastIndexOf(".")+1,fullName.length());
                        
                        Attach attach=new Attach();
                        attach.setContent(result);
                        attach.setFileType("FILE");
                        attach.setFullName(fullName);
                        attach.setName(name);
                        attach.setPrefix(prefix);
                        attach.setRefEntity(shareReference.getClass().getName());
                        attach.setRefEntityID(shareReference.getId().toString());
                        attach.setIsPublish(Integer.parseInt(isPublishs.get(i).toString()));//默认为不发布
                        
                        attachService.saveOrUpdate(attach);
                    } 
                    if(isFtps.get(i).equals("1")){
                        String productReferenceId = shareReference.getId().toString();
                        String fileName = fileNames.get(i);
                        String fullName = fileName;
                        String name = fullName.substring(0, fullName.lastIndexOf("."));
                        String prefix = fullName.substring(
                                fullName.lastIndexOf(".") + 1, fullName.length());
                        
                        Long dateFile= new Date().getTime();
                        String urlFileName = productReferenceId + "_" + dateFile + "." + prefix;
                        String contextPath = ServletActionContext.getServletContext().getRealPath("/");
                        String saveDirectory = contextPath + PropertiesUtil.readValue(
                                "/poc-ftp.properties", "ftp.path");
                        //保存绝对路径
                        String saveFilePath = saveDirectory + urlFileName;
                        FileUtils.copyFile(file, new File(saveFilePath));
                        
                        //byte[] result = new byte[BUFFER_SIZE];
                        //result = FileUtils.readFileToByteArray(file);
                        
                        FileUtils.forceDelete(file);
    
                        Attach attach = new Attach();
                        //attach.setContent(result);
                        attach.setFileType("FILE");
                        attach.setFullName(fullName);
                        attach.setName(name);
                        attach.setPrefix(prefix);
                        attach.setRefEntity(shareReference.getClass().getName());
                        attach.setRefEntityID(shareReference.getId().toString());
                        attach.setIsPublish(Integer.parseInt(isPublishs.get(i).toString()));
                        attach.setUrlFileName(urlFileName);
                        attach.setIsFtp(1);
    
                        attachService.saveOrUpdate(attach);
                        
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        //修改附件是否为发布
        String[] publishIDs=getContextObjects("publishIDs");
        String[] attachIDs=getContextObjects("attachIDs");
        int iPub=0;
        int iAttach=0;
        if (publishIDs!=null){
            iPub=publishIDs.length;
        }
        if (attachIDs!=null){
            iAttach=attachIDs.length;
        }
        String[] unpubIDs=new String[iAttach-iPub];
        for (String pID:publishIDs){
            Attach attach=(Attach)attachService.findById(Integer.parseInt(pID));
            attach.setIsPublish(1);
            attachService.update(attach);
        }
        int i=0;
        for (String attachID:attachIDs){
            boolean isExist=false;
            for (String pID:publishIDs){
                if (attachID.equalsIgnoreCase(pID)){
                    isExist=true;
                }
            }
            if (!isExist) unpubIDs[i++]=attachID;
        }
        for (String unpubID:unpubIDs){
            Attach attach=(Attach)attachService.findById(Integer.parseInt(unpubID));
            attach.setIsPublish(0);
            attachService.update(attach);
        }
        
        //删除附件
        String[] delIDs=getContextObjects("delIDs");
        if (delIDs!=null && delIDs.length>0){
            attachService.batchDel(delIDs);
        }
        //初始化数据
        init();        

        return SUCCESS;
    }
    
    /**
     * 
     * 删除操作
     * @return
     */
    public String remove()
    {
        baseService.remove(shareReference);
        return SUCCESS;
    }
    
    /**
     * 
     * 批量删除操作
     * @return
     */
    public String batchDel()
    {
        String[] ids = getContextObjects("ids");
        baseService.batchDel(ids);
        return SUCCESS;
    }
    
    /**
     * 
     * 根据关键字获取实体数据
     * @return
     */
    public String findById()
    {
        if (shareReference != null && shareReference.getId() != null && shareReference.getId() != 0)
        {
            shareReference = (P) baseService.findById(shareReference.getId());
        }
        init();
        if (StringUtils.isNotEmpty(dictType)){
            Dict dict=(Dict)dictService.findById(new Integer(dictType));
            setRefTypeName(dict.getName());
            if (shareReference==null){
                ShareReference sr=new ShareReference();
                shareReference=(P)sr;
                shareReference.setReferenceType(dict);
            }
        }
        return SUCCESS;
    }
    
    /**
     * 
     * 根据关键字获取实体数据
     * @return
     */
    public String findByPage()
    {
        super.findByPage();
        if (shareReference != null && shareReference.getId() != 0)
        {
            shareReference = (P) baseService.findById(shareReference.getId());
        }
        init();
        return SUCCESS;
    }
    
    /**
     * 
     * 根据关键字获取实体数据
     * @return
     */
    public String findByRef()
    {
        ActionContext ctx = ActionContext.getContext();        
        HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
        dictType=request.getParameter("dictType"); 
        refType=request.getParameter("refType");
        if (this.getConds() == null){
            this.setConds(new HashMap<String, Object> ());
        }
        if(dictType==null||"".equals(dictType)){
            Criterion cond1 = Restrictions.eq("keyValue",refType);
            List<DictType> ldt=this.dictTypeService.findBy(cond1);
            if (ldt!=null && ldt.size()>0){
                DictType dictType=ldt.get(0);
                this.currDictType=dictType;
                Criterion cond2 = Restrictions.eq("dictType",dictType);
                List<Dict> ld=dictService.findBy(cond2);
                if(ld!=null&&ld.size()>0){
                    Dict dict=(Dict)ld.get(0);
                    this.currDict=dict;
                    this.setRefTypeName(dict.getName());
                    this.setDictType(dict.getId().toString());
                    this.getConds().put("referenceType.id", dict.getId());
                }
            }
        }else{
            Dict dict=(Dict)dictService.findById(new Integer(dictType));
            this.setRefTypeName(dict.getName());
            this.getConds().put("referenceType.id", dict.getId());
        }
        this.findByPage();
        return SUCCESS;
    }
    
    /**
     * 
     * 查询显示所有共享资料信息
     * @return
     */
    public String findAllByRef()
    {
        itvList=this.findByType("ITV_SHARE");
        shopList=this.findByType("SHOP_SHARE");
        markList=this.findByType("MARKINFO_SHARE");
        comList=this.findByType("COMINFO_SHARE");
        mdocList=this.findByType("PROD_MDOC_SHARE");
        notRefList=this.findByType("NOT_REF_SHARE");
        bizProcList=this.findByType("BIZ_PROCESS_SHARE");
        
        weakReportList=this.findByType("MEETING_SHARE");
        ApplicationContextUtil.getHttpServletRequest().setAttribute("weakReportList", weakReportList);
        return SUCCESS;
    }


    /**
     * 组合查询条件
     * @return
     */
    public Criterion combineCond()
    {
        Criterion cond = null;
        if (super.getConds() != null)
        {
            // 遍历参数表
            Iterator i = super.getConds().entrySet().iterator();
            while (i.hasNext())
            {
                Entry entry = (Entry) i.next();
                String key = (String) entry.getKey();
                if (super.getConds().get(key) != null
                        && !StringUtils.isEmpty(super.getConds().get(key)
                                .toString()))
                {
                    // 根据实际情况做处理
                    Criterion temp = null;
                    if (key.equalsIgnoreCase("title"))
                    {
                        temp = Restrictions.like(key, "%"
                                + super.getConds().get(key).toString() + "%");
                    }
                    else
                    {
                        temp = Restrictions.eq(key, super.getConds().get(key));
                    }

                    if (cond == null)
                    {
                        cond = temp;
                    }
                    else
                    {
                        cond = Restrictions.and(cond, temp);
                    }
                }
            }
        }
        return cond;
    }

    
    public List findByType(String type)
    {
//        Criterion cond1 = Restrictions.eq("keyValue",type);
//        lRefType=dictService.findBy(cond1);
//        if (this.getConds() == null){
//            this.setConds(new HashMap<String, Object> ());
//        }
//        if(lRefType!=null&&lRefType.size()>0){
//            this.getConds().put("referenceType", lRefType.get(0));
//            pageControl = baseService.findByPage(combineCond(),1,5);
//        }
        return shareReferenceService.findShareReferenceByType(type, "6");
    }
    /**
     * 
     * 获取业务POJO
     * @return
     */
    public P getshareReference()
    {
        return shareReference;
    }
    
    /**
     * 
     * 设置业务POJO
     * @return
     */
    public void setshareReference(P shareReference)
    {
        this.shareReference = shareReference;
    }

    /**
     * 获取资料类型数据
     * @return the lRefType
     */
    public List<Dict> getLRefType()
    {
        return lRefType;
    }

    /**
     * 设置资料类型数据
     * @param refType the lRefType to set
     */
    public void setLRefType(List<Dict> refType)
    {
        lRefType = refType;
    }

    /**
     * 获取数据字典服务
     * @return the dictService
     */
    public DictService getDictService()
    {
        return dictService;
    }

    /**
     * 设置数据字典服务
     * @param dictService the dictService to set
     */
    public void setDictService(DictService dictService)
    {
        this.dictService = dictService;
    }

    /**
     * 获取附件列表数据
     * @return the attachs
     */
    public List<Attach> getAttachs()
    {
        return attachs;
    }

    /**
     * 设置附件列表数据
     * @param attachs the attachs to set
     */
    public void setAttachs(List<Attach> attachs)
    {
        this.attachs = attachs;
    }

    /**
     * 获取附件服务
     * @return the attachService
     */
    public AttachService getAttachService()
    {
        return attachService;
    }

    /**
     * 设置附件服务
     * @param attachService the attachService to set
     */
    public void setAttachService(AttachService attachService)
    {
        this.attachService = attachService;
    }
    
    public List<String> getUploadFileName()
    {
        return fileNames;
    }

    public void setUploadFileName(List<String> fileNames)
    {
        this.fileNames = fileNames;
    }

    public List<File> getUpload()
    {
        return uploads;
    }

    public void setUpload(List<File> uploads)
    {
        this.uploads = uploads;
    }

    public void setUploadContentType(List<String> contentTypes)
    {
        this.uploadContentTypes = contentTypes;
    }

    public List<String> getUploadContentType()
    {
        return this.uploadContentTypes;
    }

    public DictTypeService getDictTypeService()
    {
        return dictTypeService;
    }

    public void setDictTypeService(DictTypeService dictTypeService)
    {
        this.dictTypeService = dictTypeService;
    }

    public ShareReferenceService getShareReferenceService()
    {
        return shareReferenceService;
    }

    public void setShareReferenceService(ShareReferenceService shareReferenceService)
    {
        this.shareReferenceService = shareReferenceService;
    }

    public List<P> getShareRefList()
    {
        return shareRefList;
    }

    public void setShareRefList(List<P> shareRefList)
    {
        this.shareRefList = shareRefList;
    }

    public String getRefType()
    {
        return refType;
    }

    public void setRefType(String refType)
    {
        this.refType = refType;
    }

    public List<Dict> getLSecretType()
    {
        return lSecretType;
    }

    public void setLSecretType(List<Dict> secretType)
    {
        lSecretType = secretType;
    }

    public String getDictType()
    {
        return dictType;
    }

    public void setDictType(String dictType)
    {
        this.dictType = dictType;
    }

    public List getComList()
    {
        return comList;
    }

    public void setComList(List comList)
    {
        this.comList = comList;
    }

    public List getItvList()
    {
        return itvList;
    }

    public void setItvList(List itvList)
    {
        this.itvList = itvList;
    }

    public List getMarkList()
    {
        return markList;
    }

    public void setMarkList(List markList)
    {
        this.markList = markList;
    }

    public List getShopList()
    {
        return shopList;
    }

    public void setShopList(List shopList)
    {
        this.shopList = shopList;
    }

    /**
     * @return the refTypeName
     */
    public String getRefTypeName()
    {
        return refTypeName;
    }

    /**
     * @param refTypeName the refTypeName to set
     */
    public void setRefTypeName(String refTypeName)
    {
        this.refTypeName = refTypeName;
    }

    /**
     * @return the mdocList
     */
    public List getMdocList()
    {
        return mdocList;
    }

    /**
     * @param mdocList the mdocList to set
     */
    public void setMdocList(List mdocList)
    {
        this.mdocList = mdocList;
    }

    /**
     * @return the notRefList
     */
    public List getNotRefList()
    {
        return notRefList;
    }

    /**
     * @param notRefList the notRefList to set
     */
    public void setNotRefList(List notRefList)
    {
        this.notRefList = notRefList;
    }

    /**
     * @return the bizProcList
     */
    public List getBizProcList()
    {
        return bizProcList;
    }

    /**
     * @param bizProcList the bizProcList to set
     */
    public void setBizProcList(List bizProcList)
    {
        this.bizProcList = bizProcList;
    }

    /**
     * @return the currDictType
     */
    public DictType getCurrDictType()
    {
        return currDictType;
    }

    /**
     * @param currDictType the currDictType to set
     */
    public void setCurrDictType(DictType currDictType)
    {
        this.currDictType = currDictType;
    }

    /**
     * @return the currDict
     */
    public Dict getCurrDict()
    {
        return currDict;
    }

    /**
     * @param currDict the currDict to set
     */
    public void setCurrDict(Dict currDict)
    {
        this.currDict = currDict;
    }

    public List<String> getFtpFile()
    {
        return ftpFile;
    }

    public void setFtpFile(List<String> ftpFile)
    {
        this.ftpFile = ftpFile;
    }

    public String getFtpUrl()
    {
        return ftpUrl;
    }

    public void setFtpUrl(String ftpUrl)
    {
        this.ftpUrl = ftpUrl;
    }
    

    public String getFtpMaxSize()
    {
        return ftpMaxSize;
    }

    public void setFtpMaxSize(String ftpMaxSize)
    {
        this.ftpMaxSize = ftpMaxSize;
    }

	public List getWeakReportList() {
		return weakReportList;
	}

	public void setWeakReportList(List weakReportList) {
		this.weakReportList = weakReportList;
	}

}
